<?php
#+------------------------------------------------------------------
#| 普通的。
#+------------------------------------------------------------------
#| Author:Janmas Cromwell <janmas-cromwell@outlook.com>
#+------------------------------------------------------------------
namespace app\library\websocket;

use Swoole\WebSocket\Server;

class Websocket
{
	protected $server;

	protected $isRunning = false;

	protected $eventMounNumber = 0;

	public function __construct(string $host = '', int $port = 9501)
	{
		$this->server = new Server($host, $port);
	}

	public function on(string $event, callable $callable)
	{
		$this->server->on($event, $callable);
		++$this->eventMounNumber;
	}

	public function set(array $setting)
	{
		if ($this->isRunning) {
			throw new \Exception('请在server运行前添加配置');
		}
		if (isset($setting['log_file'])) {
			touch($setting['log_file']);
		}
		$this->server->set($setting);
	}

	public function run()
	{
		if ($this->eventMounNumber < 3) {
			throw new \Exception('Websocket最少要监听3个事件 open、message、close');
		}
		$this->server->start();
		$this->isRunning = true;
	}

}
